import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    NavBar,
    Form,
    Input,
    Button,
    Toast,
    Dialog,
    Picker,
    Popup,
    Stepper,
    Tag,
} from 'antd-mobile';
import { LeftOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import styles from './index.module.less';

interface Medicine {
    id: string;
    name: string;
    specification: string;
    usage: string;
    frequency: string;
    duration: number;
    quantity: number;
    unit: string;
    notes: string;
}

const Prescription: React.FC = () => {
    const { patientId } = useParams<{ patientId: string }>();
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [medicines, setMedicines] = useState<Medicine[]>([]);
    const [showMedicinePicker, setShowMedicinePicker] = useState(false);

    // Mock data - replace with API call
    const medicineTemplates = [
        { label: '感冒处方', value: 'cold' },
        { label: '高血压处方', value: 'hypertension' },
        { label: '糖尿病处方', value: 'diabetes' },
    ];

    const handleBack = () => {
        Dialog.confirm({
            content: '确定要离开吗？未保存的信息将会丢失',
            onConfirm: () => {
                navigate(-1);
            },
        });
    };

    const handleTemplateSelect = (value: string) => {
        // TODO: Load template content
        console.log('Selected template:', value);
    };

    const handleAddMedicine = () => {
        setShowMedicinePicker(true);
    };

    const handleMedicineSelect = (values: string[]) => {
        const newMedicine: Medicine = {
            id: Date.now().toString(),
            name: values[0],
            specification: '100mg*24片',
            usage: '口服',
            frequency: '每日3次',
            duration: 7,
            quantity: 1,
            unit: '盒',
            notes: '',
        };
        setMedicines([...medicines, newMedicine]);
        setShowMedicinePicker(false);
    };

    const handleMedicineChange = (id: string, field: keyof Medicine, value: any) => {
        setMedicines(medicines.map(medicine =>
            medicine.id === id ? { ...medicine, [field]: value } : medicine
        ));
    };

    const handleRemoveMedicine = (id: string) => {
        setMedicines(medicines.filter(medicine => medicine.id !== id));
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            console.log('Form values:', values);
            // TODO: Submit to backend
            Toast.show({
                icon: 'success',
                content: '保存成功',
            });
            navigate(`/examination/${patientId}`);
        } catch (error) {
            console.error('Form validation failed:', error);
        }
    };

    return (
        <div className={styles.container}>
            <NavBar onBack={handleBack} className={styles.navBar}>
                处方开具
            </NavBar>

            <div className={styles.content}>
                <Form
                    form={form}
                    layout="vertical"
                    className={styles.form}
                    footer={
                        <Button
                            block
                            type="submit"
                            color="primary"
                            size="large"
                            onClick={handleSubmit}
                        >
                            保存并进入检查
                        </Button>
                    }
                >
                    <Form.Item label="处方模板">
                        <Picker
                            columns={[medicineTemplates]}
                            onChange={handleTemplateSelect}
                        >
                            {(items, { open }) => (
                                <div className={styles.templatePicker} onClick={open}>
                                    <span>选择模板</span>
                                    <span className={styles.arrow}>▼</span>
                                </div>
                            )}
                        </Picker>
                    </Form.Item>

                    <Form.Item
                        name="medicines"
                        label="药品"
                        rules={[{ required: true, message: '请添加药品' }]}
                    >
                        <div className={styles.medicineList}>
                            {medicines.map((medicine) => (
                                <div key={medicine.id} className={styles.medicineItem}>
                                    <div className={styles.medicineHeader}>
                                        <span className={styles.medicineName}>{medicine.name}</span>
                                        <Button
                                            className={styles.removeBtn}
                                            onClick={() => handleRemoveMedicine(medicine.id)}
                                            icon={<DeleteOutlined />}
                                        />
                                    </div>
                                    <div className={styles.medicineSpec}>
                                        <span>{medicine.specification}</span>
                                        <Stepper
                                            min={1}
                                            value={medicine.quantity}
                                            onChange={(value) => handleMedicineChange(medicine.id, 'quantity', value)}
                                        />
                                        <span>{medicine.unit}</span>
                                    </div>
                                    <div className={styles.medicineUsage}>
                                        <Tag color="primary">{medicine.usage}</Tag>
                                        <Tag color="success">{medicine.frequency}</Tag>
                                        <span>服用{medicine.duration}天</span>
                                    </div>
                                    <Input
                                        className={styles.medicineNotes}
                                        placeholder="备注"
                                        value={medicine.notes}
                                        onChange={(value) => handleMedicineChange(medicine.id, 'notes', value)}
                                    />
                                </div>
                            ))}
                            <Button
                                className={styles.addMedicineBtn}
                                onClick={handleAddMedicine}
                                icon={<PlusOutlined />}
                            >
                                添加药品
                            </Button>
                        </div>
                    </Form.Item>
                </Form>
            </div>

            <Popup
                visible={showMedicinePicker}
                onMaskClick={() => setShowMedicinePicker(false)}
                position="bottom"
            >
                <Picker
                    columns={[['阿莫西林', '布洛芬', '维生素C', '感冒灵']]}
                    onConfirm={handleMedicineSelect}
                    onCancel={() => setShowMedicinePicker(false)}
                />
            </Popup>
        </div>
    );
};

export default Prescription; 